
#include <MultiplexD/Logging/Logger.h>

#include <Ape/IO/Console.h>

#include <MultiplexD/DaemonInstance.h>

namespace MultiplexD {
	namespace Logging {
		Logger::Logger()
				: m_LogLevel(ltDebug)
				, m_UseStdErr(false)
		{}
		Logger::~Logger() {}
		
		void Logger::Init() {
			m_Path = DaemonInstance::Get()->Options().LogFile;
			if (m_Path.ToString().IsEmpty()) {
				m_UseStdErr = true;
			}
			else {
				m_UseStdErr = false;
				m_File.SetPath(m_Path);
				m_File.Open(Ape::IO::FS::oAppendBinary);
			}
		}
		
		void Logger::SetLevel(LoggerSeverity ltSeverity) {
			m_LogLevel = ltSeverity;
		}
		
		void Logger::ProcessMessage(const WorkerModel::MultiplexLetter& letter) {
			//printf("void Logger::ProcessMessage(const WorkerModel::MultiplexLetter& letter)\n");
			
			LoggerMessageData* data = letter.GetData<LoggerMessageData>();
			Ape::String msg = data->Message;
			
			Ape::String sSeverity = "";
			switch (letter.LetterType) {
				case ltDebug:
					sSeverity = "DEBUG "; break;
				case ltNotice:
					sSeverity = "NOTICE"; break;
				case ltWarning:
					sSeverity = "WARN  "; break;
				case ltError:
					sSeverity = "ERROR "; break;
				case ltFatal:
					sSeverity = "FATAL "; break;
				default:
					sSeverity = "OTHER "; break;
			}
			if (m_UseStdErr)
				Ape::IO::StdErr << L"[" + sSeverity + L"]:\t" + msg; // + Ape::IO::NewLine;
			else {
				m_File.WriteString(L"[" + sSeverity + L"]:\t" + msg + Ape::IO::NewLine);
				m_File.Flush();
			}
		}
	}
}
